/**
 * Notes: 数据库集合初始化
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY ABS Abition Tech
 * Date: 2024-05-25
 */

const cloudBase = require('../../../framework/cloud/cloud_base.js');
const config = require('../../../config/config.js');
const util = require('../../../framework/helpers/util.js');
const timeUtil = require('../../../framework/helpers/time_util.js');

class InitCloudCollections {

	/**
	 * 初始化云开发环境的集合和索引
	 * @returns {Promise<Object>} 初始化结果
	 */
	static async initCollections() {
		console.log('>> 开始初始化PLM研发项目数据库...');
		
		try {
			// 获取数据库连接
			const db = cloudBase.getDatabase();
			
			// 基本集合定义
			const collections = [
				{ name: 'plm_research_project', indexes: [
					{ fields: { createTime: -1 }, name: 'createTime_desc' },
					{ fields: { level1: 1, level2: 1 }, name: 'status_level' }
				]},
				{ name: 'plm_research_project_history', indexes: [
					{ fields: { projectId: 1, createTime: -1 }, name: 'project_history' }
				]},
				{ name: 'plm_branch', indexes: [
					{ fields: { projectId: 1, isMaster: -1 }, name: 'branch_project' }
				]},
				{ name: 'plm_document', indexes: [
					{ fields: { projectId: 1, docType: 1 }, name: 'doc_project' }
				]},
				{ name: 'plm_member', indexes: [
					{ fields: { projectId: 1, role: 1 }, name: 'member_project' }
				]}
			];
			
			// 逐个初始化集合
			for (const collection of collections) {
				await this._initCollection(db, collection.name, collection.indexes);
			}
			
			// 创建测试数据
			await this.createTestData();
			
			console.log('>> PLM研发项目数据库初始化完成!');
			
			return {
				code: 0,
				message: '初始化成功'
			};
		} catch (error) {
			console.error('>> PLM研发项目数据库初始化失败!', error);
			
			return {
				code: -1,
				message: '初始化失败: ' + error.message
			};
		}
	}
	
	/**
	 * 初始化单个集合
	 * @param {Object} db 数据库对象
	 * @param {String} collectionName 集合名称
	 * @param {Array} indexes 索引配置
	 */
	static async _initCollection(db, collectionName, indexes = []) {
		try {
			// 检查集合是否存在 - 改用尝试获取集合的方法检查存在性
			let exists = false;
			try {
				// 尝试获取，如果不存在会抛出错误
				await db.collection(collectionName).count();
				exists = true;
				console.log(`>> 集合 ${collectionName} 已存在，无需创建`);
			} catch (error) {
				if (error.errCode === -502005 || error.message.includes('not exist')) {
					// 集合不存在
					exists = false;
				} else {
					throw error; // 其他错误，抛出
				}
			}
			
			if (!exists) {
				// 创建集合
				console.log(`>> 创建集合: ${collectionName}`);
				await db.createCollection(collectionName);
				console.log(`>> 集合 ${collectionName} 创建成功!`);
			}
			
			// 清理测试数据
			try {
				await db.collection(collectionName).where({
					TEST_FLAG: true
				}).remove();
				console.log(`>> 集合 ${collectionName} 的临时记录已清理`);
			} catch (error) {
				console.warn(`>> 清理集合 ${collectionName} 的临时记录失败:`, error.message);
			}
			
			// 创建索引
			if (indexes && indexes.length > 0) {
				for (const index of indexes) {
					try {
						console.log(`>> 为集合 ${collectionName} 创建索引: ${index.name}`);
						await db.collection(collectionName).createIndex(index.fields, { name: index.name });
					} catch (error) {
						// 如果是已存在索引的错误，或环境不支持，则跳过
						if (error.errCode === -502002 || error.message.includes('not support')) {
							console.log(`>> 索引 ${index.name} 已存在或环境不支持索引创建，跳过`);
						} else {
							console.error(`>> 创建索引 ${index.name} 失败:`, error);
						}
					}
				}
			}
			
			return true;
		} catch (error) {
			console.error(`>> 初始化集合 ${collectionName} 失败:`, error);
			throw error;
		}
	}
	
	/**
	 * 创建测试数据
	 */
	static async createTestData() {
		try {
			console.log('>> 开始创建测试数据...');
			
			const db = cloudBase.getCloud().database();
			const projectCollection = db.collection('plm_research_project');
			
			// 检查是否已有测试数据
			const count = await projectCollection.count();
			
			if (count && count.total > 0) {
				console.log(`>> 已有 ${count.total} 条项目数据，进行检查...`);
				
				// 检查是否有足够的测试数据
				if (count.total >= 5) {
					console.log('>> 测试数据数量足够，跳过创建');
					return;
				}
				
				console.log('>> 测试数据不足，将创建额外的测试数据');
			}
			
			// 创建几条测试项目数据
			const now = Math.floor(Date.now() / 1000);
			const testProjects = [
				{
					_id: 'test-project-001',
					model: 'ABS-HC2024',
					projectType: '霍尔',
					projectTypeName: '霍尔传感器',
					customerName: '测试客户A',
					priority: 'normal',
					description: '这是一个测试项目，用于展示项目列表功能',
					startDate: now,
					deadline: now + 86400 * 30,
					level1: 1,
					developmentStatus: '开发中',
					completionPercentage: 30,
					createTime: now,
					updateTime: now,
					projectLead: '张工程师',
					department: '研发部',
					extData: {
						voltage: '5V',
						current: '20mA',
						controlType: '数字'
					}
				},
				{
					_id: 'test-project-002',
					model: 'ABS-M2024',
					projectType: '磁',
					projectTypeName: '磁传感器',
					customerName: '测试客户B',
					priority: 'high',
					description: '高优先级磁传感器项目',
					startDate: now,
					deadline: now + 86400 * 20,
					level1: 2,
					developmentStatus: '测试中',
					completionPercentage: 75,
					createTime: now,
					updateTime: now,
					projectLead: '李工程师',
					department: '研发部',
					extData: {
						voltage: '12V',
						current: '50mA',
						controlType: '模拟'
					}
				},
				{
					_id: 'test-project-003',
					model: 'ABS-A2024',
					projectType: '角度',
					projectTypeName: '角度传感器',
					customerName: '测试客户C',
					priority: 'normal',
					description: '角度测量传感器项目',
					startDate: now - 86400 * 10,
					deadline: now + 86400 * 50,
					level1: 1,
					developmentStatus: '开发中',
					completionPercentage: 45,
					createTime: now - 86400 * 10,
					updateTime: now,
					projectLead: '王工程师',
					department: '研发部',
					extData: {
						voltage: '3.3V',
						current: '15mA',
						controlType: '数字'
					}
				},
				{
					_id: 'test-project-004',
					model: 'ABS-ME2024',
					projectType: '霍尔',
					projectTypeName: '霍尔传感器',
					customerName: '测试客户D',
					priority: 'urgent',
					description: '紧急的霍尔传感器项目',
					startDate: now - 86400 * 5,
					deadline: now + 86400 * 15,
					level1: 2,
					developmentStatus: '测试中',
					completionPercentage: 85,
					createTime: now - 86400 * 5,
					updateTime: now,
					projectLead: '赵工程师',
					department: '研发部',
					extData: {
						voltage: '24V',
						current: '100mA',
						controlType: '数模混合'
					}
				},
				{
					_id: 'test-project-005',
					model: 'ABS-S2024',
					projectType: '速度',
					projectTypeName: '速度传感器',
					customerName: '测试客户E',
					priority: 'low',
					description: '低优先级速度传感器项目',
					startDate: now - 86400 * 20,
					deadline: now + 86400 * 60,
					level1: 1,
					developmentStatus: '开发中',
					completionPercentage: 20,
					createTime: now - 86400 * 20,
					updateTime: now - 86400 * 2,
					projectLead: '钱工程师',
					department: '研发部',
					extData: {
						voltage: '9V',
						current: '30mA',
						controlType: '数字'
					}
				}
			];
			
			// 批量添加测试数据
			console.log('>> 开始添加测试数据...');
			
			for (const project of testProjects) {
				try {
					// 检查项目是否已存在
					const existing = await projectCollection.doc(project._id).get();
					
					if (existing && existing.data && existing.data.length > 0) {
						console.log(`>> 项目 ${project._id} 已存在，跳过创建`);
						continue;
					}
					
					// 添加新项目
					await projectCollection.add({
						data: project
					});
					
					console.log(`>> 成功添加项目: ${project.model}`);
				} catch (err) {
					console.error(`>> 添加项目 ${project._id} 失败:`, err);
				}
			}
			
			console.log('>> 测试数据创建完成');
			
		} catch (error) {
			console.error('>> 创建测试数据失败:', error);
		}
	}
}

module.exports = InitCloudCollections; 